/**
 * 接种点管理脚本
 */

// 全局变量
let currentPage = 1;
let pageSize = 10;
let isEditMode = false;

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 检查登录状态和权限
    if (!Auth.isLoggedIn()) {
        window.location.href = '../login.html';
        return;
    }

    if (!Auth.checkRole(UserRole.SUPER_ADMIN)) {
        UI.showMessage('您没有权限访问此页面', 'danger');
        setTimeout(() => {
            Auth.logout();
        }, 2000);
        return;
    }

    // 初始化页面
    initPage();
});

/**
 * 初始化页面
 */
async function initPage() {
    // 显示用户信息
    displayUserInfo();

    // 加载接种点列表
    await loadSiteList();
}

/**
 * 显示用户信息
 */
function displayUserInfo() {
    const userInfo = Auth.getUserInfo();
    if (userInfo) {
        const userName = document.getElementById('userName');
        const userAvatar = document.getElementById('userAvatar');

        if (userName) userName.textContent = userInfo.account || '超级管理员';
        if (userAvatar) userAvatar.textContent = (userInfo.account || 'S').charAt(0).toUpperCase();
    }
}

/**
 * 加载接种点列表
 */
async function loadSiteList() {
    try {
        UI.showLoading();

        // 后端返回的是数组，不是分页对象
        const sites = await HttpClient.get('/admin/vaccination-site/list');

        displaySiteList(sites || []);

        UI.hideLoading();
    } catch (error) {
        console.error('加载接种点列表失败:', error);
        UI.hideLoading();
        UI.showMessage('加载数据失败: ' + error.message, 'danger');
    }
}

/**
 * 显示接种点列表
 */
function displaySiteList(sites) {
    const tbody = document.getElementById('siteTableBody');

    if (!sites || sites.length === 0) {
        tbody.innerHTML = '<tr><td colspan="6" class="text-center">暂无数据</td></tr>';
        return;
    }

    tbody.innerHTML = sites.map(site => `
        <tr>
            <td>${site.id}</td>
            <td>${site.name || '-'}</td>
            <td>${site.address || '-'}</td>
            <td>${site.phoneNum || '-'}</td>
            <td>
                <button class="btn btn-sm btn-primary" onclick="showEditModal(${site.id})">
                    <i class="fas fa-edit"></i> 编辑
                </button>
                <button class="btn btn-sm btn-danger" onclick="handleDelete(${site.id}, '${site.name}')">
                    <i class="fas fa-trash"></i> 删除
                </button>
            </td>
        </tr>
    `).join('');
}

/**
 * 显示分页
 */
function displayPagination(data) {
    const pagination = document.getElementById('pagination');
    const totalPages = data.pages || 1;

    if (totalPages <= 1) {
        pagination.innerHTML = '';
        return;
    }

    let html = '<div class="pagination-container">';

    // 上一页
    html += `<button class="pagination-btn" ${currentPage === 1 ? 'disabled' : ''} onclick="changePage(${currentPage - 1})">上一页</button>`;

    // 页码
    for (let i = 1; i <= totalPages; i++) {
        if (i === 1 || i === totalPages || (i >= currentPage - 2 && i <= currentPage + 2)) {
            html += `<button class="pagination-btn ${i === currentPage ? 'active' : ''}" onclick="changePage(${i})">${i}</button>`;
        } else if (i === currentPage - 3 || i === currentPage + 3) {
            html += '<span class="pagination-ellipsis">...</span>';
        }
    }

    // 下一页
    html += `<button class="pagination-btn" ${currentPage === totalPages ? 'disabled' : ''} onclick="changePage(${currentPage + 1})">下一页</button>`;

    html += '</div>';
    pagination.innerHTML = html;
}

/**
 * 切换页码
 */
async function changePage(page) {
    currentPage = page;
    await loadSiteList();
}

/**
 * 显示添加模态框
 */
function showAddModal() {
    isEditMode = false;
    document.getElementById('modalTitle').textContent = '添加接种点';
    document.getElementById('siteForm').reset();
    document.getElementById('siteId').value = '';
    document.getElementById('siteModal').classList.add('show');
}

/**
 * 显示编辑模态框
 */
async function showEditModal(id) {
    try {
        UI.showLoading();

        // 获取接种点列表（后端返回数组）
        const sites = await HttpClient.get('/admin/vaccination-site/list');
        const site = sites.find(s => s.id === id);

        if (!site) {
            throw new Error('接种点不存在');
        }

        isEditMode = true;
        document.getElementById('modalTitle').textContent = '编辑接种点';
        document.getElementById('siteId').value = site.id;
        document.getElementById('siteName').value = site.name || '';
        document.getElementById('siteAddress').value = site.address || '';
        document.getElementById('sitePhone').value = site.phoneNum || '';

        document.getElementById('siteModal').classList.add('show');

        UI.hideLoading();
    } catch (error) {
        console.error('加载接种点详情失败:', error);
        UI.hideLoading();
        UI.showMessage('加载数据失败: ' + error.message, 'danger');
    }
}

/**
 * 关闭模态框
 */
function closeModal() {
    document.getElementById('siteModal').classList.remove('show');
    document.getElementById('siteForm').reset();
}

/**
 * 处理表单提交
 */
async function handleSubmit() {
    const form = document.getElementById('siteForm');

    // 表单验证
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }

    const siteId = document.getElementById('siteId').value;
    const data = {
        name: document.getElementById('siteName').value.trim(),
        address: document.getElementById('siteAddress').value.trim(),
        phoneNum: document.getElementById('sitePhone').value.trim()
    };

    try {
        UI.showLoading();

        if (isEditMode && siteId) {
            // 编辑
            await HttpClient.put(`/admin/vaccination-site/${siteId}`, data);
            UI.showMessage('编辑成功', 'success');
        } else {
            // 添加
            await HttpClient.post('/admin/vaccination-site', data);
            UI.showMessage('添加成功', 'success');
        }

        closeModal();
        await loadSiteList();

        UI.hideLoading();
    } catch (error) {
        console.error('保存失败:', error);
        UI.hideLoading();
        UI.showMessage('保存失败: ' + error.message, 'danger');
    }
}

/**
 * 处理删除
 */
function handleDelete(id, name) {
    UI.confirm(`确定要删除接种点"${name}"吗？`, async () => {
        try {
            UI.showLoading();

            await HttpClient.delete(`/admin/vaccination-site/${id}`);

            UI.showMessage('删除成功', 'success');
            await loadSiteList();

            UI.hideLoading();
        } catch (error) {
            console.error('删除失败:', error);
            UI.hideLoading();
            UI.showMessage('删除失败: ' + error.message, 'danger');
        }
    });
}

/**
 * 退出登录
 */
function handleLogout() {
    UI.confirm('确定要退出登录吗？', () => {
        Auth.logout();
    });
}

